let form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"), types = getQueryVariable("types");
$('#editor-form').find('input,textarea,select').attr('disabled',true);
layui.use(['tableEdit'], function () {
    let layer = layui.layer;
//签约日期默认当天
    laydate.render({
        elem: '#signTime',
        type: 'date',
        value: new Date(),
    });

//签约单位
    let complaintUnit = [];
    $.ajax({
        url: "company/getAllMakerUnit",
        success: function (res) {
            if (res.status == 200) {
                complaintUnit = res.data;
                $.each(res.data, function (index, item) {
                    if(item){
                        $("#companyCode").append(new Option(item.name, item.code));
                    }
                });
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
//供应商
    $.ajax({
        url: "customer2/getAllInspectUnit",
        success: function (res) {
            if (res.status == 200) {
                $.each(res.data, function (index, item) {
                    $("#supplierCode").append(new Option(item.name, item.code));
                });
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    function selectAddress(code){
        $.ajax({
            type: 'POST',
            url: "purchase/selectCustomer2ByCode",
            data: {"code":code},
            dataType: "json",
            success: function (res) {
                let deliverAddress = "";
                let accountPeriod = "";
                if (res.status == 200) {
                    deliverAddress = res.data.deliverAddress;
                    accountPeriod = res.data.accountPeriod;
                } else {
                    layer.msg("付款账期、交货地点 "+res.msg, {icon: 3});
                }
                form.val("editor-form", {
                    "deliverAddress": deliverAddress,
                    "paymentTime": accountPeriod,
                })

                $.ajax({
                    type: 'GET',
                    url: "customer2contact/selectByPage",
                    data: {"pageNum":1,"pageSize":1,"company":code},
                    dataType: "json",
                    async:false,
                    success: function (res) {
                        if (res.status == 200) {
                            if(res.data.length>0){
                                form.val("editor-form", {
                                    "contactPerson": res.data[0].name,
                                    "contactEmail": res.data[0].email,
                                })
                            }else{
                                layer.msg("暂无联系方式", {icon: 3});
                            }
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });
            }
        });

    }

    let loginUserCode = user.code;//当前登录用户编码
    let executorList = [];
    $.ajax({
        url:"user/getAllUserNameAndCode",
        success:function(res){
            if(res.status == 200){
                executorList = res.data;
                $.each(res.data, function (index, item) {
                    $("#executor").append(new Option(item.name, item.code));
                    $("#salesman").append(new Option(item.name, item.code));
                });
                if (id != "") {
                    queryById();
                }else{
                    $("#executor").val(loginUserCode);
                }
                $("#invoiceStatus").val(1);//默认开票：是
                form.render('select');
            }else{
                layer.msg(res.msg, {icon: 5});
            }
        }
    });

    let currencyList = [];
//获取币种
    $.ajax({
        url:"receivePayment/getCurrencyInfo",
        success:function(res){
            let rmbCode = ""
            if(res.status == 200){
                currencyList = res.data;
                let rmbRate = 0;
                for(let i in res.data){
                    if(res.data[i].englishName == "USD"){
                        //美元->人民币 汇率
                        rmbRate = res.data[i].exchangeRate;
                    }
                    if(res.data[i].englishName == "RMB"){
                        //人民币编码
                        rmbCode = res.data[i].code;
                        //人民币
                        rmbName = res.data[i].name;
                        //美元汇率
                        $("#usdRate").val(res.data[i].exchangeRate);
                    }
                    $('#currency').append(new Option(res.data[i].name, res.data[i].code));
                }
                if(rmbCode.length > 0){
                    //默认RMB选中
                    $('#currency').val(rmbCode);
                    $('#rmbRate').val(rmbRate);
                }
                form.render('select');
            }
        }
    });
// let currencyList = getdictionary(5, 14);//币种列表
    let paymentTypeList = getdictionary(5, 17);//付款类型
    let colourList = getdictionary(6, 41);//颜色
    let unitList = getdictionary(6, 42);//单位
    let bankList = [];//银行列表

// for (let i in currencyList) {
//     $('#currency').append(new Option(currencyList[i].name, currencyList[i].code));
// }
    for (let i in paymentTypeList) {
        $('#paymentType').append(new Option(paymentTypeList[i].name, paymentTypeList[i].code));
    }

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    form.render('select');


    let productList = [];
    let wjCatalogCode = "purchase";//文件编码
    let fileList = [];
    let logList = [];

//表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "executorCode": "进入修改",
        })
        // $("#purchaseOrderNo").attr("readonly", true);
    }/*else{
    let dataJson = {
        "type": "CG",
    };
    $.ajax({
        type: 'POST',
        url: 'number/numberByTypeAndDate',
        data: JSON.stringify(dataJson),
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if (res.data != "") {
                    form.val("editor-form", {
                        "purchaseOrderNo": res.data,
                    })
                }
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error: function (data) {
            layer.msg(data.msg, {icon: 5});
        }
    });
}*/


    //--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: productList,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cellMinWidth: 120,
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            // {field: 'productImg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'salesContractNo', title: '销售合同号'},
            {field: 'chineseName', title: '中文名称',style:"overflow:hidden" },
            {field: 'productNo', title: '产品编码'},
            {field: 'specNo', title: '规格编码'},
            {field: 'normExplain', title: '规格说明',style:"overflow:hidden"},
            {field: 'chineseDesc', title: '中文描述',style:"overflow:hidden"},
            {field: 'englishDesc', title: '英文描述',style:"overflow:hidden"},

            {field: 'materialSupplier', title: '素材供应商', width: 240},
            {field: 'costPrice', title: '产品单价', edit: 'text', totalRow: true,
                templet: function(d){
                    let costPrice = d.costPrice?d.costPrice:0;
                    return Number(costPrice).toFixed(6)
                }
            },
            {field: 'taxedCostPrice', title: '产品-含税单价', hide: true, totalRow: true,
                templet: function(d){
                    let taxedCostPrice = d.taxedCostPrice?d.taxedCostPrice:0.0000;
                    return Number(taxedCostPrice).toFixed(4)
                }
            },
            {field: 'untaxedCostPrice', title: '产品-未税单价', hide: true, totalRow: true,
                templet: function(d){
                    let untaxedCostPrice = d.untaxedCostPrice?d.untaxedCostPrice:0.0000;
                    return Number(untaxedCostPrice).toFixed(4)
                }
            },
            {field: 'amount', title: '数量', edit: 'text', totalRow: true,
                templet: function(d) {
                    return d.amount?Number(d.amount).toFixed(2):0.00;
                }},
            {field: 'price', title: '采购成本', totalRow: true,
                templet: function(d) {
                    let costPrice = d.costPrice?d.costPrice:0.00;
                    let otherPrice = d.otherPrice?d.otherPrice:0.00;
                    let amount = d.amount?d.amount:0.00;
                    let price = 0.0000;
                    if(amount==0){
                        price = costPrice;
                    }else{
                        price = (Number(costPrice)+Number(otherPrice/amount)).toFixed(6);
                    }
                    return price;
                },
            },
            {field: 'otherPrice', title: '其他费用', edit: 'text', totalRow: true,
                templet: function(d){
                    let otherPrice = d.otherPrice?d.otherPrice:0.0000; return Number(otherPrice).toFixed(4);
                }
            },
            {field: 'otherDesc', title: '费用备注', edit: 'text'},
            {field: 'priceSubtotal', title: '成本金额小计', totalRow: true,
                templet: function(d) {
                    let costPrice = d.costPrice?d.costPrice:0.00;
                    let otherPrice = d.otherPrice?d.otherPrice:0.00;
                    let amount = d.amount?d.amount:0.00;
                    let price = 0.0000;
                    if(amount==0){
                        price = costPrice;
                    }else{
                        price = (Number(costPrice)+Number(otherPrice/amount)).toFixed(6);
                    }
                    return (amount*price).toFixed(6);
                },
            },
            {field: 'requestDeliveryDate', title: '要求交货日期',
                /*templet:function(d){
                    return layui.util.toDateString(d.requestDeliveryDate,"yyyy-MM-dd");
                }*/
                templet:function(d){
                    return '<input type="text" value="'+layui.util.toDateString(d.requestDeliveryDate,"yyyy-MM-dd")+'"  class="layui-input layui-input-date">';
                }
            },
            {field: 'unit', title: '单位'/*, templet: '#unitScript'*/,
                templet: function(data) {
                    let name = "";
                    $.each(unitList, function(index, item) {
                        if (data.unit==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    if(data.unit){
                        if(name==""){
                            name = data.unit;
                        }
                    }
                    return name;
                },
            },
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
            {field: 'colour', title: '颜色',
                templet: function(data) {
                    let name = "";
                    $.each(colourList, function(index, item) {
                        if (data.colour==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    if(data.colour){
                        if(name==""){
                            name = data.colour;
                        }
                    }
                    return name;
                }
            },
            {field: 'grossWeight', title: '毛重',
                templet: function(d){
                    let grossWeight = d.grossWeight?d.grossWeight:0.00; return Number(grossWeight).toFixed(2);
                }
            },
            {field: 'grossSubtotal', title: '毛重小计',
                templet: function(d) {
                    let grossSubtotal = d.grossSubtotal?d.grossSubtotal:0.00; return Number(grossSubtotal).toFixed(2);
                }},
            {field: 'netWeight', title: '净重', edit: 'text',
                templet: function(d) {
                    let netWeight = d.netWeight?d.netWeight:0.00; return Number(netWeight).toFixed(2);
                }},
            {field: 'netSubtotal', title: '净重小计', edit: 'text',
                templet: function(d) {
                    let netSubtotal = d.netSubtotal?d.netSubtotal:0.00; return Number(netSubtotal).toFixed(2);
                }},
            {field: 'volume', title: '体积', edit: 'text',
                templet: function(d) {
                    let volume = d.volume?d.volume:0.00; return Number(volume).toFixed(2);
                }
            },
            {field: 'trayNumber', title: '托数', edit: 'text',
                templet: function(d) {
                    let trayNumber = d.trayNumber?d.trayNumber:0.00; return Number(trayNumber).toFixed(2);
                }
            },
            {field: 'trayCapacity', title: '每托量', edit: 'text',
                templet: function(d) {
                    let trayCapacity = d.trayCapacity?d.trayCapacity:0.00; return Number(trayCapacity).toFixed(2);
                }
            },
            {field: 'numberOfPiece', title: '箱数', edit: 'text', totalRow: true,
                templet: function(d) {
                    let numberOfPiece = d.numberOfPiece?d.numberOfPiece:0.00; return Number(numberOfPiece).toFixed(2);
                }
            },
            {field: 'qty', title: '每箱数量', edit: 'text', totalRow: true, totalRowType:'double',
                templet: function(d) {
                    let qty = d.qty?d.qty:0.00; return Number(qty).toFixed(2);
                }
            },
            {field: 'payTime', title: '付款账期', edit: 'text'},
            {field: 'untaxedPrice', title: '未税单价', style:"overflow:hidden", totalRow: true,
                templet: function(d){
                    let untaxedPrice = d.untaxedPrice?d.untaxedPrice:0.0000; return Number(untaxedPrice).toFixed(4);
                }
            },
            {field: 'untaxedPriceSubtotal', title: '未税金额小计', style:"overflow:hidden", totalRow: true, totalRowType: "double4",
                templet: function(d){
                    let untaxedPriceSubtotal = d.untaxedPriceSubtotal?d.untaxedPriceSubtotal:0.00; return Number(untaxedPriceSubtotal).toFixed(2);
                }
            },
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 440,
        done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css("overflow","visible")
            $(".layui-form-select").parent(".layui-table-cell").css("overflow","visible")
            $(".layui-input-date").each((i,e)=>{
                laydate.render({
                    elem:e,
                    format: 'yyyy-MM-dd',
                    type: 'date',
                    trigger: 'click',
                    theme: '#393D49',
                    calendar: true,
                    done(data){
                        let tableData = table.cache["storageproductstableid"];
                        tableData[i]["requestDeliveryDate"] = data;
                        table.reload('storageproductstableid',{data:tableData});
                    }
                });
            })
            //合计采购成本、成本金额小计
            let priceSum = 0;
            layui.each(res.data, function (index, d) {
                let costPrice = d.costPrice ? d.costPrice : 0.00;
                let otherPrice = d.otherPrice ? d.otherPrice : 0.00;
                let amount = d.amount ? d.amount : 0.00;
                let price = 0.0000;
                if (amount == 0) {
                    price = Number(costPrice);
                } else {
                    price = (Number(costPrice) + Number(otherPrice / amount)).toFixed(6);
                }
                priceSum = (Number(priceSum) + Number(price)).toFixed(6);
            })
            this.elem.next().find('.layui-table-total td[data-field="price"] .layui-table-cell').text(priceSum);
            if(types=="1"){//成品
                $(".accessories").css('display','none');
            }else if(types=="2"){
                $(".finishedProduct").css('display','none');
            }
            $("#purchaseType").val(types)
            let purchaseTotalPrice = 0;
            let earnestRate = $("#earnestRate").val()==""?0:$("#earnestRate").val();//定金比例
            let earnestMoney = $("#earnestMoney").val()==""?0:$("#earnestMoney").val();//定金金额
            let isTaxIncluded = $("#taxIncluded").val()==""?0:Number($("#taxIncluded").val());//是否含税  1 含税  2 不含税
            let modulus = 1;//含税系数
            if(isTaxIncluded==1){
                modulus=1.13
            }

            let salesContractNos = $("#salesContractNo").val();//销售合同号
            if(salesContractNos!=""){
                salesContractNos+=",";
            }
            if(res.data.length>0){
                let purchaseOrderNo = $("#purchaseOrderNo").val();
                if(!purchaseOrderNo){
                    form.val("editor-form", {
                        "purchaseOrderNo": res.data[0].salesContractNo,
                    })
                }
                let salesmanVal = res.data[0].salesmanCode?res.data[0].salesmanCode:$("#salesman").val();
                $("#salesman").val(salesmanVal);
                let customerLevelCode = res.data[0].customerLevelCode?res.data[0].customerLevelCode:$("#customerLevelCode").val();
                $("#customerLevelCode").val(customerLevelCode);
                let customerLevelName = res.data[0].customerLevelName?res.data[0].customerLevelName:$("#customerLevelName").val();
                $("#customerLevelName").val(customerLevelName);

                let remark = $("#remark").val();
                if(!remark){
                    form.val("editor-form", {
                        "remark": res.data[0].importRemark,
                    })
                }

                for (let i in colourList) {
                    $('.colourSelect').append(new Option(colourList[i].name, colourList[i].code));
                }
                for (let i in unitList) {
                    $('.unitSelect').append(new Option(unitList[i].name, unitList[i].code));
                }
                let paymentTime = $("#paymentTime").val()==""?"":$("#paymentTime").val();//付款账期

                let signingName = '';
                let bankName = '';
                let priceSubtotalSum = 0;
                for (let i = 0; i < res.data.length; i++) {
                    // let tempId = res.data[i].tempId?res.data[i].tempId:res.data[i].id;
                    let tempId = res.data[i].tempId!=undefined?res.data[i].tempId:i;
                    res.data[i].tempId = tempId;
                    if(res.data[i].signingCode){
                        if(res.data[i].signingName){
                            if(res.data[i].signingName!=signingName){
                                let isExist = false;
                                $.each(complaintUnit,function (index,item) {
                                    if(item.code==res.data[i].signingCode){
                                        isExist = true;
                                        return;
                                    }
                                })
                                if(!isExist){
                                    complaintUnit.push({code:res.data[i].signingCode,name:res.data[i].signingName})
                                }
                                signingName = res.data[i].signingName;
                            }
                        }
                    }

                    if(res.data[i].bankCode){
                        if(res.data[i].bankName){
                            if(res.data[i].bankName!=bankName){
                                let isExist = false;
                                $.each(bankList,function (index,item) {
                                    if(item.code==res.data[i].bankCode){
                                        isExist = true;
                                        return;
                                    }
                                })
                                if(!isExist){
                                    bankList.push({code:res.data[i].bankCode,name:res.data[i].bankName})
                                }
                                bankName = res.data[i].bankName;
                            }
                        }
                    }

                    selectBlueprintFileByCode(res.data[i].productNo, res.data[i].specNo);
                    //销售合同号
                    if(res.data[i].salesContractNo!=undefined){
                        if(salesContractNos.indexOf(res.data[i].salesContractNo) == -1){
                            salesContractNos += res.data[i].salesContractNo+",";
                        }
                    }
                    $("#colour_" + tempId).val(res.data[i].colour);
                    $("#unit_" + tempId).val(res.data[i].unit);
                    if(res.data[i].amount>0){
                        let price = 0.0000;
                        if(res.data[i].amount==0){
                            price = res.data[i].costPrice;
                        }else{
                            price = (Number(res.data[i].costPrice)+Number(res.data[i].otherPrice/res.data[i].amount)).toFixed(6);
                        }
                        res.data[i].price = Number(price).toFixed(6);
                        let priceSubtotal = (price*res.data[i].amount).toFixed(2);
                        res.data[i].priceSubtotal = priceSubtotal;
                        priceSubtotalSum = (Number(priceSubtotalSum) + Number(priceSubtotal)).toFixed(2);
                        purchaseTotalPrice += res.data[i].priceSubtotal*1;//采购总额
                        //未税金额
                        res.data[i].untaxedPrice = (price/modulus).toFixed(4);
                        res.data[i].untaxedPriceSubtotal = (res.data[i].amount*res.data[i].untaxedPrice).toFixed(4);
                        if(res.data[i].trayCapacity>0){
                            res.data[i].trayNumber = res.data[i].amount/res.data[i].trayCapacity;
                        }else if(res.data[i].trayNumber>0){
                            res.data[i].trayCapacity = res.data[i].amount/res.data[i].trayNumber;
                        }
                        if(res.data[i].qty>0){
                            res.data[i].numberOfPiece = res.data[i].amount/res.data[i].qty;
                        }else if(res.data[i].numberOfPiece>0){
                            res.data[i].qty = res.data[i].amount/res.data[i].numberOfPiece;
                        }
                    }else{
                        res.data[i].trayNumber = res.data[i].trayCapacity = 0.00;
                        res.data[i].qty = res.data[i].numberOfPiece = 0.00;
                    }

                    res.data[i].grossSubtotal = res.data[i].amount*res.data[i].grossWeight;
                    res.data[i].netSubtotal = res.data[i].amount*res.data[i].netWeight;

                    res.data[i].payTime = paymentTime;
                    let $tr = $('#storageproducts').next().find('tbody tr').eq(i);
                    let updateList = [
                        'price',
                        'priceSubtotal',
                        'untaxedPrice',
                        'untaxedPriceSubtotal',
                        'trayCapacity',
                        'trayNumber',
                        'numberOfPiece',
                        'qty',
                        'grossSubtotal',
                        'netSubtotal',
                        'payTime',
                    ];
                    updateList.forEach(function (e) {
                        $tr.find(`[data-field="${e}"] div`).text(res.data[i][e]?res.data[i][e]:'');
                    })
                    // $tr.find('[data-field="costPrice"] div').text(res.data[i].costPrice);
                    // $tr.find('[data-field="untaxedPriceSubtotal"] div').text(res.data[i].untaxedPriceSubtotal);
                    // $tr.find('[data-field="trayCapacity"] div').text(res.data[i].trayCapacity);
                    // $tr.find('[data-field="trayNumber"] div').text(res.data[i].trayNumber);
                    // $tr.find('[data-field="numberOfPiece"] div').text(res.data[i].numberOfPiece);
                    // $tr.find('[data-field="qty"] div').text(res.data[i].qty);
                    // $tr.find('[data-field="payTime"] div').text(paymentTime);
                }
                this.elem.next().find('.layui-table-total td[data-field="priceSubtotal"] .layui-table-cell').text(priceSubtotalSum);

                if (salesContractNos.indexOf(",")!=-1){
                    salesContractNos=salesContractNos.substring(0,salesContractNos.length-1);
                }
            }
            if(purchaseTotalPrice>0){
                earnestMoney = (purchaseTotalPrice*earnestRate/100).toFixed(4);
            }else if(purchaseTotalPrice>0 && earnestMoney>0){
                earnestRate = (earnestMoney/purchaseTotalPrice*100).toFixed(4);
            }

            form.val("editor-form", {
                "purchaseTotalPrice": purchaseTotalPrice.toFixed(2),
                "earnestRate": earnestRate,
                "earnestMoney": earnestMoney,
                "salesContractNo": salesContractNos,
            });
            // hoverOpenImg();//显示大图
            //重载签约公司和银行
            reloadCBSelect();
            form.render('select');
        }
    });

    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        // if(obj.field == "costPrice"){
        //     if(obj.value*1>old*1){
        //         layer.msg('不可大于原成本价');
        //         $(this).val(old);
        //         return;
        //     }
        // }
        if(obj.field == "amount"){
            if(obj.value*1>old*1){
                layer.msg('不可大于原数量');
                $(this).val(old);
                return;
            }
        }
        let isTaxIncluded = $("#taxIncluded").val()==""?0:$("#taxIncluded").val();//是否含税  1 含税  2 不含税
        let modulus = 1;//含税系数
        if(isTaxIncluded==1){
            modulus=1.13
        }
        //金额
        if (obj.field == "amount" || obj.field == "price" || obj.field == "priceSubtotal" || obj.field == "costPrice"
            || obj.field == "otherPrice" || obj.field == "untaxedPrice" || obj.field == "untaxedPriceSubtotal") {
            if(!isNumber(obj.value)){
                layer.msg('请输入数字');
                $(this).val(old);
                return;
            }
            obj.data.costPrice = obj.data.costPrice?obj.data.costPrice:0.0000;
            obj.data.otherPrice = obj.data.otherPrice?obj.data.otherPrice:0.0000;
            obj.data.amount = obj.data.amount?obj.data.amount:0.00;
            let price = 0.0000;
            if(obj.data.amount==0){
                price = obj.data.costPrice;
            }else{
                price = (Number(obj.data.costPrice)+Number(obj.data.otherPrice/obj.data.amount)).toFixed(4);
            }
            obj.data.price = price;
            obj.data.priceSubtotal = (obj.data.amount*price).toFixed(2);
            obj.update({
                price:obj.data.price,
                priceSubtotal:obj.data.priceSubtotal,
                untaxedPrice:(obj.data.price/modulus).toFixed(4),
                untaxedPriceSubtotal:(obj.data.amount*price/modulus).toFixed(2),
            })


            let purchaseTotalPrice = 0;
            let earnestRate = $("#earnestRate").val();
            let $tr = $('#storageproducts').next().find('tbody tr [data-field="priceSubtotal"] div');
            $tr.each(function () {
                var priceSubtotal= $(this).text()
                purchaseTotalPrice += priceSubtotal*1;
            })

            form.val("editor-form", {
                "purchaseTotalPrice": purchaseTotalPrice.toFixed(2),
                "earnestMoney": (purchaseTotalPrice*earnestRate/100).toFixed(4),
            });
            form.render('select');
        }

        if (obj.field == "grossWeight" || obj.field == "grossSubtotal"
            || obj.field == "netWeight" || obj.field == "netSubtotal"
            || obj.field == "volume" || obj.field == "trayNumber"
            || obj.field == "trayNumber" || obj.field == "trayCapacity"
            || obj.field == "numberOfPiece" || obj.field == "qty"
            || obj.field == "outPackLength" || obj.field == "outPackWidth"
            || obj.field == "outPackHeight" || obj.field == "outPackSize"
            || obj.field == "outPackNum") {
            if(!isNumber(obj.value)){
                layer.msg('请输入数字');
                $(this).val(old);
                return;
            }
            if(obj.value=="0"){
                layer.msg('请输入非零数');
                $(this).val(old);
                return;
            }
            if(obj.field == "trayNumber"){
                obj.update({
                    trayCapacity:(obj.data.amount/obj.data.trayNumber).toFixed(2),
                })
            }
            if(obj.field == "trayCapacity"){
                obj.update({
                    trayNumber:(obj.data.amount/obj.data.trayCapacity).toFixed(2),
                })
            }

            if(obj.field == "numberOfPiece"){
                obj.update({
                    qty:(obj.data.amount/obj.data.numberOfPiece).toFixed(2),
                })
            }
            if(obj.field == "qty"){
                obj.update({
                    numberOfPiece:(obj.data.amount/obj.data.qty).toFixed(2),
                })
            }

            obj.update({
                grossSubtotal:(obj.data.amount*obj.data.grossWeight).toFixed(2),
                netSubtotal:(obj.data.amount*obj.data.netWeight).toFixed(2),
            })
        }


    });

//付款账期
    $("#paymentTime").on("input",function(e){
        let paymentTime = e.delegateTarget.value;
        let $tr = $('#storageproducts').next().find('tbody tr [data-field="payTime"] div');
        $tr.each(function () {
            $(this).text(paymentTime)
        })
    });

//定金比例
    let earnestRateMax = 100.00;//定金比例最大值
    $("#earnestRate").on("input",function(e){
        let purchaseTotalPrice = $("#purchaseTotalPrice").val()?$("#purchaseTotalPrice").val():0.0000;
        let earnestRate = e.delegateTarget.value;
        let earnestMoney = 0;
        if(earnestRate>earnestRateMax){
            layer.msg('定金比例不可大于100');
            $("#earnestRate").val(earnestRateMax);
            earnestMoney = purchaseTotalPrice;
        }else{
            earnestMoney = (purchaseTotalPrice*earnestRate/100).toFixed(4);
        }
        $("#earnestMoney").val(earnestMoney);
    });

//定金金额
    $("#earnestMoney").on("input",function(e){
        let purchaseTotalPrice = $("#purchaseTotalPrice").val()?$("#purchaseTotalPrice").val():0.0000;
        let earnestMoney = e.delegateTarget.value;
        let earnestRate = (earnestMoney/purchaseTotalPrice*100).toFixed(4);
        if(earnestRate>earnestRateMax){
            layer.msg('生成的定金比例不可大于100');
            $("#earnestMoney").val(0);
            return ;
        }
        $("#earnestRate").val(earnestRate);
    });

    form.on("select(supplierFilter)", function (data) {
        let text = $('#supplierCode option:selected').text()
        $("#supplierName").val(text);
        selectAddress(data.value);
    });
// 是否含税
    form.on("select(taxFilter)", function (data) {
        table.reload('storageproductstableid');
    });

    form.on("select(colourSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["colour"] = data.value;
            }
        });
    });
    form.on("select(unitSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["unit"] = data.value;
            }
        });
    });

    form.on("select(complaintUnitSelect)", function (data) {
        let complaintUnitCode = data.value;
        let text = $('#companyCode option:selected').text()
        $("#companyName").val(text);
        let selectCode = 0;
        if(id==""){
            selectCode=0;
        }
        bankSelect(complaintUnitCode,selectCode);
    });

    form.on("select(currencyFilter)", function (data) {
        let usdRate = 0;
        $.each(currencyList, function (index, item) {
            if(data.value == "usd-001"){
                usdRate = 1;
                return;
            }else if (data.value == item.code){
                usdRate = item.exchangeRate;
                return;
            }
        })
        form.val("editor-form", {
            "usdRate": usdRate,
        });
    });

    table.on('tool(storageproductstable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('确认删除?', function (index) {
                let oldData =  table.cache["storageproductstableid"];

                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                reloadCBSelect();
                layer.close(index);
            });
        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'salesoffinished':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/ExportBusiness/tpl/salesoffinished.jsp'
                });
                break;
            case 'stockupfinished':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/ExportBusiness/tpl/stockupfinished.jsp'
                });
                break;
            case 'stockupaccessories':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/ExportBusiness/tpl/stockupaccessories.jsp'
                });
                break;
            case 'salesaccessories':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/ExportBusiness/tpl/salesaccessories.jsp'
                });
                break;
            case 'dels':
                var data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.id);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        var cbList = table.cache["storageproductstableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        }
        ;
    });
//---费用
    table.render({
        elem: '#cost'
        , data: []
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'costtype', title: '费用类型', templet: '#costtypeselect'}
            , {field: 'amount', title: '金额', event: 'amount'}
            , {field: 'descr', title: '备注说明'}
        ]]
        , id: 'costtableid'
        , height: 380
        , page: true
    });
    table.on('edit(costtable)', function (obj) {
        var old = $(this).prev().text();//旧值
        //判断数据类型 ,,,,,,,
        if ((obj.field == "amount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
    });
    form.on("select(costtypeselect_filter)", function (data) {
        var elem = data.othis.parents("tr");
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["costtableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["costtype"] = data.value;
            }
        });
    });

    table.on('toolbar(costtable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        switch (obj.event) {
            case 'new':
                var oldData = table.cache["costtableid"];
                var data1 = {"id": oldData.length + 1, costtype: "", amount: "", descr: ""};
                oldData.push(data1);
                table.reload('costtableid', {data: oldData});
                break;
            case 'del':
                var data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.id);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        var cbList = table.cache["costtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("costtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        }
        ;
    });


//---附件
    table.render({
        elem: '#attachment'
        , data: fileList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            // {field: 'fileName', title: '文件名称', fixed: true,style:"overflow:hidden"},
            {field: 'wjName', title: '文件名称', fixed: true,style:"overflow:hidden", event: "wjname"},
            {field: 'fileUrl', title: '文件路径', fixed: true,style:"overflow:hidden"},
            {field: 'fileType', title: '文件类型', fixed: true},
            {field: 'fileSize', title: '文件大小(KB)', fixed: true},
            {field: 'fileExecutor', title: '操作员', fixed: true,
                templet: function(data) {
                    let name = "";
                    $.each(executorList, function(index, item) {
                        if (data.fileExecutor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            },
            {field: 'fileUploadTime', title: '上传时间', fixed: true,
                templet: function(d) {
                    return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
                }
            },
            {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: 'uploadify'
        , accept: 'file'
        , data:{"fileType":"purchase"}
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var newfilename = "";
                if (ispd(wjCatalogCode, file.name)) {
                    // newfilename = getFileName(file.name);
                    // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                    layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                        layer.close(index);
                    });
                }
                if (newfilename != "") {
                    var obj = {};
                    obj.code = index;
                    obj.name = newfilename;
                    fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + newfilename + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }else{
                    var obj = {};
                    obj.code = index;
                    obj.name = file.name;
                    // fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }
            });
        }
        , done: function (res, index, upload) {
            var filename = "";
            for (var i = 0; i < uploadlist.length; i++) {
                if (uploadlist[i].code == index) {
                    filename = uploadlist[i].name;
                    break;
                }
            }
            if (res.data.length > 0) {
                var files = res.data;
                var filepaths = [];
                for (var i = 0; i < files.length; i++) {
                    var obj = {};
                    obj.fileName = files[i].fileName;
                    obj.ftpPath = files[i].ftpPath;
                    filepaths.push(obj);
                }
                if (savefile(filepaths, filename, wjCatalogCode)) {
                    let oldData = fileList;
                    let newData = [];
                    let num = oldData.length+1;
                    for(let i in files){
                        let newFile = {};
                        // fileList[i].tempId = num;
                        newFile.fileName = files[i].fileName;
                        newFile.wjName = files[i].originalFileName;
                        newFile.fileUrl = files[i].ftpPath;
                        newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                        newData.push(newFile);
                        num++;
                    }
                    oldData.push.apply(oldData, newData);
                    fileList = oldData;
                    table.reload('attachmenttableid', {data:fileList});
                }

                var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            /* if (res.files.file) { //上传成功
                 var tr = $("#uploadlist").find('tr#upload-' + index)
                     , tds = tr.children();
                 tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                 tds.eq(3).html(''); //清空操作
                 return delete this.files[index]; //删除文件队列已经上传成功的文件
             }*/
            this.error(index, upload);
        }
        , error: function (index, upload) {
            let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data : fileList}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });

    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoadNew(data.wjName, data.fileUrl+'/'+data.fileName);
        } else if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                let oldData =  fileList;
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].id == obj.data.id) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('attachmenttableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }

        if(obj.event==='wjname'){
            onLineFile(data.fileUrl+'/'+data.fileName)
        }
    });

    //---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: logList
        , cols: [[
            {field: 'upType', title: '操作类型',
                templet: function(data) {
                    let name = "";
                    switch (data.upType){
                        case 1: name = "新增"; break;
                        case 2: name = "删除"; break;
                        case 3: name = "更新"; break;
                    }
                    return name;
                }
            }
            , {field: 'upModel', title: '修改对象',
                templet: function(data) {
                    let name = "";
                    switch (data.upModel){
                        case 1: name = "采购主表"; break;
                        case 2: name = "采购产品"; break;
                    }
                    return name;
                }
            }
            , {field: 'upUser', title: '修改人员：编码'}
            , {field: 'upTime', title: '修改日期',
                templet: function (data){
                    return layui.util.toDateString(data.upTime,"yyyy-MM-dd HH:mm:ss")
                }
            }
            , {field: 'upContext', title: '修改内容'}
        ]]
        ,id: 'logtableid'
        ,height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
    });

    function hoverOpenImg() {
        let img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }


    function queryById() {
        $.ajax({
            type: 'POST',
            url: 'purchase/selectByKey/' + id,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                debugger
                if (res.status == 200) {
                    if(res.data){
                        form.val("editor-form", {
                            "purchaseOrderNo": res.data.purchaseOrderNo,
                            "purchaseType": res.data.purchaseType,
                            "supplierName": res.data.supplierName,
                            "contactPerson": res.data.contactPerson,
                            "contactEmail": res.data.contactEmail,
                            "salesContractNo": res.data.salesContractNo,
                            "companyCode": res.data.companyCode,
                            "companyName": res.data.companyName,
                            "signTime": res.data.signTime,
                            "bank": res.data.bank,
                            "deliverDate": res.data.deliverDate,
                            "deliverAddress": res.data.deliverAddress,
                            "currency": res.data.currency,
                            "rmbRate": res.data.rmbRate,
                            "usdRate": res.data.usdRate,
                            "purchaseTotalPrice": res.data.purchaseTotalPrice,
                            "executorCode": res.data.executorCode,
                            "salesmanCode": res.data.salesmanCode,
                            "executorName": res.data.executorName,
                            "salesmanName": res.data.salesmanName,
                            "remark": res.data.remark,
                            "sn": res.data.sn,
                            "paymentType": res.data.paymentType,
                            "paymentTime": res.data.paymentTime,
                            "earnestRate": res.data.earnestRate,
                            "earnestMoney": res.data.earnestMoney,
                            "totalApplication": res.data.totalApplication,
                            "invoiceStatus": res.data.invoiceStatus,
                            "taxIncluded": res.data.taxIncluded,
                            "editTime":res.data.editTime,
                            "boxStatus": res.data.boxStatus,
                            "customerLevelCode" : res.data.customerLevelCode,
                            "customerLevelName" : res.data.customerLevelName,
                            "whetherCreditGuarantee" : res.data.whetherCreditGuarantee,
                            "creditGuaranteeAmount" : res.data.creditGuaranteeAmount,
                            "whetherToReplenish" : res.data.whetherToReplenish,
                            "customerComplaintNo" : res.data.customerComplaintNo,
                            "modeOfTrade" : res.data.modeOfTrade
                        });
                        laydate.render({
                            elem: '#deliverDate',
                            type: 'date',
                            value: new Date(res.data.deliverDate),
                        });
                        laydate.render({
                            elem: '#signTime',
                            type: 'date',
                            value: new Date(res.data.signTime),
                        });
                        bankSelect(res.data.companyCode,res.data.bank);
                        productList = selectProductByPuId(id);
                        table.reload('storageproductstableid',{data : productList, limit:productList.length});
                        fileList = selectFileByPuId(id);
                        table.reload('attachmenttableid',{data : fileList});
                        selectLogByPuId(id);
                        table.reload('logtableid',{data : logList});
                    }else{
                        layer.msg("初始化失败!");
                    }
                } else {
                    layer.msg("初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("初始化失败!");
            }
        });
    }

//产品
    function selectProductByPuId(puId) {
        let obj = [];
        $.ajax({
            async: false,
            type: 'POST',
            url: 'purchase/selectProductByPuId/'+puId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                if (res.status == 200) {
                    if(res.data.length>0){
                        obj = res.data;

                        form.val("editor-form",{
                            "productNo": res.data.productNo,
                            "specNo": res.data.specNo,
                            "normExplain": res.data.normExplain,
                            "chineseName": res.data.chineseName,
                            "englishName": res.data.englishName,
                            "chineseDesc": res.data.chineseDesc,
                            "englishDesc": res.data.englishDesc,
                            "unit": res.data.unit,
                            "colour": res.data.colour,
                            "customerArticleNo": res.data.customerArticleNo,
                            "price": res.data.price,
                            "costPrice": res.data.costPrice,
                            "taxedCostPrice": res.data.taxedCostPrice,
                            "untaxedCostPrice": res.data.untaxedCostPrice,
                            "otherPrice": res.data.otherPrice,
                            "otherDesc": res.data.otherDesc,
                            "amount": res.data.amount,
                            "priceSubtotal": res.data.priceSubtotal,
                            "untaxedPrice": res.data.untaxedPrice,
                            "untaxedPriceSubtotal": res.data.untaxedPriceSubtotal,
                            "grossWeight": res.data.grossWeight,
                            "grossSubtotal": res.data.grossSubtotal,
                            "netWeight": res.data.netWeight,
                            "netSubtotal": res.data.netSubtotal,
                            "volume": res.data.volume,
                            "trayNumber": res.data.trayNumber,
                            "trayCapacity": res.data.trayCapacity,
                            "numberOfPiece": res.data.numberOfPiece,
                            "qty": res.data.qty,
                            "payTime": res.data.payTime,
                            "salesContractNo": res.data.salesContractNo,
                        })
                    }else{
                        // layer.msg(res.msg, {icon : 0})
                    }
                }else{
                    layer.msg("产品初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("产品初始化失败!");
            }
        });
        return obj;
    }
//附件
    function selectFileByPuId(puId) {
        let obj = [];
        $.ajax({
            async: false,
            type: 'POST',
            url: 'purchase/selectFileByPuId/'+puId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length>0){
                        obj = res.data;
                        form.val("editor-form", {
                            "id":"",
                            "wjName": res.data.wjName,
                            // "fileName": res.data.fileName,
                            "fileUrl": res.data.fileUrl,
                            "fileType": res.data.fileType,
                            "fileSize": res.data.fileSize,
                            "fileExecutor": res.data.fileExecutor,
                            "fileUploadTime": res.data.fileUploadTime,
                        })
                    }else{
                        // layer.msg("暂无附件数据",{icon:3});
                    }
                }else{
                    // layer.msg(res.msg,{icon:3});
                }
            },
            error: function (data) {
                layer.msg("附件初始化失败!");
            }
        });
        return obj;
    }

//附件
    function selectBlueprintFileByCode(proCode,specNo) {
        let params = {
            productNo : proCode,
            specNo : specNo,
        };
        let obj = [];
        $.ajax({
            async: false,
            type: 'POST',
            data: JSON.stringify(params),
            url: 'purchase/selectBlueprintFileByCode',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length>0){
                        obj = res.data;
                        $.each(res.data,function (index,item) {
                            item.id = "";
                            fileList.push(item);
                        })
                        // form.val("editor-form", {
                        //     "fileName": res.data.fileName,
                        //     "fileUrl": res.data.fileUrl,
                        //     "fileType": res.data.fileType,
                        //     "fileSize": res.data.fileSize,
                        //     "fileExecutor": res.data.fileExecutor,
                        //     "fileUploadTime": res.data.fileUploadTime,
                        // })
                        table.reload('attachmenttableid',{data : obj});
                        form.render('select');
                    }else{
                        // layer.msg("暂无附件数据",{icon:3});
                    }
                }else{
                    // layer.msg(res.msg,{icon:3});
                }
            },
            error: function (data) {
                layer.msg("附件初始化失败!");
            }
        });
        return obj;
    }

    //日志
    function selectLogByPuId(puId) {
        $.ajax({
            async: false,
            type: 'POST',
            url: 'purchase/selectLogByPuId/' + puId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                if (res.status == 200) {
                    logList = res.data;
                }
            },
            error: function (data) {
                layer.msg("日志初始化失败!");
            }
        });
    }

    function insert(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'purchase/insert',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data>0) {
                        tf = true;
                        layer.msg("保存成功!",{icon: 6});
                    } else {
                        layer.msg(res.msg+"保存失败", {icon: 5});
                    }
                } else {
                    layer.msg(res.msg+"保存失败",{icon: 7});
                }
            },
            error: function (data) {
                layer.msg("保存失败!",{icon: 2});
            }
        });
        return tf;
    }

    function update(data) {
        // data.editTime = layui.util.toDateString(new Date(),"yyyy-MM-dd");
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'purchase/update',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data>0) {
                        tf = true;
                        layer.msg("保存成功!",{icon: 6});
                    } else {
                        layer.msg(res.msg+"保存失败", {icon: 5});
                    }
                } else {
                    layer.msg("请求失败!",{icon: 7});
                }
            },
            error: function (data) {
                layer.msg("保存失败!",{icon: 2});
            }
        });
        return tf;
    }

    //监听附件提交
    form.on('submit(form-element)', function (data) {
        let reqData = {
            "id" : id,
            "fileList": fileList
        };
        let flag = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(reqData),
            url: 'purchase/updatePurchaseFile/'+id,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data>0) {
                        tf = true;
                        layer.msg("保存成功!",{icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/ExportBusiness/procurement.jsp");
                            parent.intab("views/jsp/ExportBusiness/procurement.jsp", "采购")
                            parent.detab("views/jsp/ExportBusiness/tpl/viewprocurement.jsp?id="+ id+"&types="+types);
                        }, 1000);
                    } else {
                        layer.msg("保存失败", {icon: 5});
                    }
                } else {
                    layer.msg("请求失败!",{icon: 7});
                }
                return false;
            },
            error: function (data) {
                layer.msg("保存失败!",{icon: 2});
            }
        });
    });

//按签约公司编号 查询对应银行
    function bankSelect(code,selectCode){
        $("#bank").empty();
        $.ajax({
            url: "bank/selectByCompanyCode",
            data: {"CompanyCode":code},
            success: function (res) {
                if (res.status == 200) {
                    $.each(res.data, function (index, item) {
                        bankList = res.data;
                        $("#bank").append(new Option(item.bankname, item.bankcode));
                    });
                    $.each(res.data,function (i,n) {
                        let isExist = false;
                        $.each(bankList,function (j,m) {
                            if(m.code==n.bankCode){
                                isExist = true;
                                return;
                            }
                        })
                        if(!isExist){
                            bankList.push({code:n.bankCode,name:n.bankName})
                        }
                    })

                    // bankList = res.data;
                    if(selectCode!=0){
                        $.each(bankList, function (index, item) {
                            if (item.bankcode==selectCode){
                                $("#bank").val(item.bankcode);
                            }
                        });
                        let bank = $("#bank").val();
                        if(bank==""){
                            $("#bank").append(new Option(selectCode, selectCode));
                            $("#bank").val(selectCode);
                        }
                    }
                    form.render('select');
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

//重载签约公司和银行
    function reloadCBSelect() {
        let companyCode = $("#companyCode").val();
        $("#companyCode").empty();
        complaintUnit.push({code:'',name:''});
        $.each(complaintUnit, function (index, item) {
            if(item){
                $("#companyCode").append(new Option(item.name, item.code));
            }
        });
        $("#companyCode").val(companyCode);
        $("#bankCode").empty();
        bankList.push({code:'',name:''});
        $.each(bankList, function (index, item) {
            $("#bankCode").append(new Option(item.name, item.code));
        });
        form.render('select');
    }

//获取文件目录下所有的文件名
    function ispd(wjCatalogCode, filename) {
        /* fileNames=[];*/
        var cun = false;
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"wjCatalogCode": wjCatalogCode, "name": filename},
            url: 'wjinfo/ispd',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data == 0 ? false : true;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    function getFileName(filename) {
        /* fileNames=[];*/
        var cun = "";
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"filename": filename},
            url: 'wjinfo/getFileName',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    //判断文件名是否重复
    function iscf(filename) {
        var tf = false;
        for (var i = 0; i < fileNames.length; i++) {
            if (filename == fileNames[i]) {
                tf = true;
                break;
            }
        }
        return tf;
    }

    //保存上传的文件
    function savefile(filepaths, filename, wjCatalogCode) {
        var tf = false;
        $.ajax({
            type: 'post',
            data: {
                "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
                "name": JSON.stringify(filename)
            },
            url: 'wjinfo/savefile',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = da.data == 0 ? false : true;
                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return tf;
    }

});